# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
import json

from itemadapter import ItemAdapter

from scrapy.utils.project import get_project_settings
import pymysql


class MysqlPipeline:
    def open_spider(self, spider):
        settings = get_project_settings()
        self.host = settings['DB_HOST']
        self.port = settings['DB_PORT']
        self.user = settings['DB_USER']
        self.password = settings['DB_PASSWORD']
        self.name = settings['DB_NAME']
        self.charset = settings['DB_CHARSET']

        self.connect()

    def connect(self):
        self.conn = pymysql.connect(
            host=self.host,
            port=self.port,
            user=self.user,
            password=self.password,
            db=self.name,
            charset=self.charset
        )

        self.cursor = self.conn.cursor()
        # self.producer = kafkaproducer(value_serializer=lambda v: json.dumps(v).encode('gbk'),
        #                               boostrap_servers=['master:9092'])

    # def process_item_to_kafka(self, item):
    #     tmp = {
    #             'content': item["content"]
    #
    #     }
    #     self.producer.send('danmu_list',tmp)
    #     pass

    def process_item(self, item, spider):

        sql = 'insert into video_barrage(bvid,bmode,userid,content,sendtime) values ("{}","{}","{}","{}","{}")'.format(item['bvid'],item['bmode'],item['userid'],item['content'],item['sendtime'])
        # self.process_item_to_kafka(item)
        self.cursor.execute(sql)
        self.conn.commit()
        return item

    def close_spider(self, spider):
        self.cursor.close()
        self.conn.close()


# class VideobarragePipeline(object):
#     def __init__(self):
#         self.file = open('data.json', 'w', encoding='utf-8')
#     def process_item(self, item, spider):
#         line = json.dumps(dict(item), ensure_ascii=False) + "\n"
#         self.file.write(line)
#         return item
#     def open_spider(self, spider):
#         pass
#     def close_spider(self, spider):
#         pass
